package com.cfm880.webview;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    private WebView mWebView;
    private ScrollView mScrollView;
    private TextView tvTitle;
    private ImageView imUp, imCenter, imDown;
    ObjectAnimator longTimeAnimator, shortTimeAnimator;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tvTitle.setText(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                WebViewUtils.injectCSS(MainActivity.this, mWebView, "style.css");
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100){
                    mWebView.setVisibility(View.INVISIBLE);
                    view.loadUrl("javascript:" +
                            "$('nav').hide();" +
                            "$('#j_footer').hide();" +
                            "$('#wx_pic').hide();" );
                    mWebView.setVisibility(View.VISIBLE);
                    mScrollView.setFocusable(false);
                    imCenter.requestFocus();
                    longTimeAnimator = ObjectAnimator.ofFloat(mWebView, "translationY", 0, 0-mWebView.getMeasuredHeight() + mScrollView.getBottom()).setDuration(60000);

                    longTimeAnimator.start();
                    longTimeAnimator.setAutoCancel(true);
                    longTimeAnimator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {
                            imCenter.setImageResource(R.drawable.pause);
                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            imCenter.setImageResource(R.drawable.play);
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {
                            imCenter.setImageResource(R.drawable.play);

                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {
                            imCenter.setImageResource(R.drawable.pause);
                        }
                    });
                    step = (int) mScrollView.getHeight()/25*2;
                }
            }
        });
        mWebView.loadUrl("http://news.sina.cn/gn/2016-10-24/detail-ifxwztru7056939.d.html?from=wap");
    }

    private void init() {
        mContentView = findViewById(R.id.activity_main);
        mScrollView = (ScrollView) findViewById(R.id.web_container);
        mScrollView.requestDisallowInterceptTouchEvent(true);
        mWebView = (WebView) findViewById(R.id.news_web_view);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        imUp = (ImageView) findViewById(R.id.im_up);
        imCenter = (ImageView) findViewById(R.id.im_center);
        imDown = (ImageView) findViewById(R.id.im_down);
        imCenter.requestFocus();

        imUp.setOnClickListener(this);
        imCenter.setOnClickListener(this);
        imDown.setOnClickListener(this);
        shortTimeAnimator = new ObjectAnimator();

    }
    //
    int flag = 0;
    long time = 0;
    int step = 1000;
    int toPosition = 0;
    int tempPosition = 0;
    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.im_up:
                toPosition = tempPosition + step;
                if (toPosition>0){
                    ObjectAnimator.ofFloat(mWebView,"translationY", tempPosition, 0).setDuration(100).start();
                    Toast.makeText(getBaseContext(), "已到顶了",Toast.LENGTH_SHORT).show();
                    tempPosition = 0;
                } else {
                    ObjectAnimator.ofFloat(mWebView,"translationY", tempPosition, toPosition).setDuration(100).start();
                    tempPosition = toPosition;
                }
                break;
            case R.id.im_center:
                if (flag == 0) {
                    flag = 1;
                    time = longTimeAnimator.getCurrentPlayTime();
                    System.out.println(longTimeAnimator);
//                    longTimeAnimator.end();
                    longTimeAnimator.cancel();
                    imCenter.setImageResource(R.drawable.play);
                }else {
                    flag = 0;
                    longTimeAnimator.start();
                    longTimeAnimator.setCurrentPlayTime(time);
                    imCenter.setImageResource(R.drawable.pause);
                }
                break;
            case R.id.im_down:
                longTimeAnimator.end();
                toPosition = tempPosition - step;
                if (toPosition<=-mWebView.getMeasuredHeight()+ mScrollView.getBottom()){
                    ObjectAnimator.ofFloat(mWebView, "translationY", tempPosition, -mWebView.getMeasuredHeight() + mScrollView.getBottom()).setDuration(100);
                    tempPosition = -mWebView.getMeasuredHeight()+ mScrollView.getBottom();
                    Toast.makeText(getBaseContext(), "已到底了",Toast.LENGTH_SHORT).show();
                }else {
                    ObjectAnimator.ofFloat(mWebView,"translationY", tempPosition, toPosition).setDuration(100).start();
                    tempPosition = toPosition;
                }
                break;

        }

    }
    private void hide() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    //  按键处理
    int flagFullScreen=0;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_0){
            if (flagFullScreen == 0) {
                flagFullScreen = 1;
                delayedHide(UI_ANIMATION_DELAY);
            } else {
                flagFullScreen = 0;
               show();
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}
